package com.zbcz.crm


import FollowPersonAdapter
import android.app.DatePickerDialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Spinner
import androidx.activity.viewModels
import com.zbcz.crm.bean.VisitData
import com.zbcz.crm.databinding.ActivityAddVisitorBinding
import com.zbcz.crm.util.IS_TEST_MODE
import com.zbcz.crm.util.ToastUtils
import com.zbcz.crm.util.UPLOAD_FORMAT
import com.zbcz.crm.util.formatDate
import com.zbcz.crm.util.getCurrentDateFormatted
import com.zbcz.crm.util.onSingleClick
import com.zbcz.crm.viewmodel.VisitorAddViewModel
import java.util.Calendar


class VisitorAddActivity : BaseActivity() {


    private lateinit var mBinding: ActivityAddVisitorBinding

    private val mAddVisitViewModel: VisitorAddViewModel by viewModels()

    private var mFollowerAdapter: FollowPersonAdapter? = null

    private var mSelectedCarryingElectronic: String? = null

    private var mCurrentDate: String? = null

    companion object {
        const val TAG = "VisitorAddActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityAddVisitorBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        init()
    }

    private fun init() {
        mBinding.ivBack.setOnClickListener {
            finish()
        }
        mBinding.tvDate.onSingleClick {
            showDatePickerDialog(this)
        }
        mBinding.edDate.onSingleClick {
            showDatePickerDialog(this)
        }
        mBinding.edDate.text = getCurrentDateFormatted()
        mBinding.spCarryingElectronic.adapter
        initSpinner(mBinding.spCarryingElectronic)
        mBinding.ivAddContacts.onSingleClick {
            //addShadowLayout()
            mAddVisitViewModel.addTestFollowers()
        }
        mFollowerAdapter = FollowPersonAdapter()
        mBinding.rcAddFollowers.adapter = mFollowerAdapter?.apply {
            mDelClick = { it, it1 ->
                mAddVisitViewModel.removeFollower(it)
            }
        }
        mAddVisitViewModel.mFollowersList.observe(this) {
            mFollowerAdapter?.submitList(it)
        }
        mBinding.tvConfirm.onSingleClick {
            validateFields()
        }
        mBinding.edPurpose.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                // 在文本变化之前执行的操作，这里不需要处理
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 文本变化时执行的操作，更新 TextView 显示输入的字符数
                mBinding.tvPurposeCount.text = "${s?.length ?: 0}/300"
            }

            override fun afterTextChanged(s: Editable?) {
                // 在文本变化之后执行的操作，这里不需要处理
            }
        })
        mCurrentDate = getCurrentDateFormatted(UPLOAD_FORMAT)
        mAddVisitViewModel.mResponse.observe(this) { isSuccess ->
            if (isSuccess) {
                finish()
            }
        }
        addTestData()
    }

    private fun showDatePickerDialog(context: Context) {
        // 获取当前日期
        val calendar: Calendar = Calendar.getInstance()
        val year: Int = calendar.get(Calendar.YEAR)
        val month: Int = calendar.get(Calendar.MONTH)
        val dayOfMonth: Int = calendar.get(Calendar.DAY_OF_MONTH)

        // 创建日期选择Dialog，并设置默认选中的日期为当前日期
        val datePickerDialog = DatePickerDialog(
            context, R.style.CustomDatePickerDialogTheme,
            { _, year, month, dayOfMonth -> // 处理日期选择结果
                mBinding.edDate.text = formatDate(year, month, dayOfMonth)
                mCurrentDate = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT)
            }, year, month, dayOfMonth
        )
        // 设置日期选择Dialog的样式为日历样式
        datePickerDialog.datePicker.calendarViewShown = true
        datePickerDialog.datePicker.spinnersShown = false // 隐藏下拉式的年份和月份选择器
        // 显示日期选择Dialog
        datePickerDialog.show()
    }

    private fun initSpinner(spinner: Spinner) {
        // 准备数据源
        val options = arrayOf("是", "否")
        // 创建适配器
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, options)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        // 设置适配器
        spinner.adapter = adapter

        // 设置选项选中监听器
        // 设置选项选中监听器
        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                // 获取选中的选项
                val selectedOption = options[position]
                Log.i(TAG, "selected$selectedOption")
                mSelectedCarryingElectronic = selectedOption
                // 处理选项选中后的逻辑，这里简单地显示一个Toast
                //Toast.makeText(this@VisitorAddActivity, "你选择了：$selectedOption", Toast.LENGTH_SHORT).show()
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有选项被选中时的处理逻辑
            }
        }
    }

//    private fun addShadowLayout() {
//        // 创建新的ShadowLayout实例
//        val shadowLayout = ShadowLayout(this)
//        shadowLayout.layoutParams = LinearLayout.LayoutParams(
//            LinearLayout.LayoutParams.MATCH_PARENT,
//            LinearLayout.LayoutParams.WRAP_CONTENT
//        )
//
//        // 将你的布局添加到ShadowLayout中
//        View.inflate(this, R.layout.item_add_followers, shadowLayout) // 替换成要添加的布局文件
//        // 将ShadowLayout添加到父容器中
//        shadowLayout.findViewById<View>(R.id.iv_del)?.onSingleClick {
//            mBinding.llAddFollowers.removeView(shadowLayout)
//        }
//        mBinding.llAddFollowers.addView(shadowLayout)
//    }


    private fun validateFields(): Boolean {
        val userName = mBinding.edUserName.text.toString().trim()
        val userIdCard = mBinding.edTvUserIdCard.text.toString().trim()
        val cellphone = mBinding.edCellphone.text.toString().trim()
        val department = mBinding.edDepartment.text.toString().trim()
        val date = mBinding.edDate.text.toString().trim()
        val purpose = mBinding.edPurpose.text.toString().trim()
        val visitedPerson = mBinding.edVisitedPerson.text.toString().trim()
        val visitedPersonPhone = mBinding.edVisitedPersonCellphone.text.toString().trim()

        // 手机号正则表达式
        val phoneRegex = "^1[3-9]\\d{9}$".toRegex()
        // 身份证号正则表达式
        val idCardRegex = "^\\d{17}[\\dXx]$".toRegex()

        // 检查所有的 EditText 是否为空
        if (userName.isEmpty()) {
            ToastUtils.show("请输入本人名称")
            return false
        }

        if (userIdCard.isEmpty()) {
            ToastUtils.show("请输入本人身份证")
            return false
        } else if (!userIdCard.matches(idCardRegex)) {
            ToastUtils.show("身份证格式不正确")
            return false
        }

        if (cellphone.isEmpty()) {
            ToastUtils.show("请输入手机号码")
            return false
        } else if (!cellphone.matches(phoneRegex)) {
            ToastUtils.show("手机号格式不正确")
            return false
        }

        if (department.isEmpty()) {
            ToastUtils.show("请输入本人单位")
            return false
        }

        if (date.isEmpty()) {
            ToastUtils.show("请选择访问日期")
            return false
        }

        if (purpose.isEmpty()) {
            ToastUtils.show("请输入访问目的")
            return false
        }
        if (visitedPerson.isEmpty()) {
            ToastUtils.show("请输入被访问人")
            return false
        }

        if (visitedPersonPhone.isEmpty()) {
            ToastUtils.show("请输入访问人手机号")
            return false
        }
        val mFollowers = mFollowerAdapter?.getAllEditTextValues()
        Log.i(TAG, mFollowers.toString())

        val mVisitData = VisitData(
            carryingElectronic = mSelectedCarryingElectronic,
            followPersonVos = mFollowers,
            visitArea = "拜访区域",
            visitDate = mCurrentDate ?: "",
            visitOrderStatus = "1",
            visitPurpose = purpose,
            visitingPersonMobileNo = visitedPersonPhone,
            visitingPersonName = visitedPerson,
            visitorEmployer = department,
            visitorIdNo = userIdCard,
            visitorMobileNo = cellphone,
            visitorName = userName
        )
        mAddVisitViewModel.submitOrder(mVisitData)
        return true
    }

    private fun addTestData() {
        if (IS_TEST_MODE) {
            mBinding.edUserName.setText("张三")
            mBinding.edTvUserIdCard.setText("110101199001012345")
            mBinding.edCellphone.setText("13800138000")
            mBinding.edDepartment.setText("测试部门")
            mBinding.edDate.setText("2024-04-09")
            mBinding.edPurpose.setText("测试目的")
            mBinding.edVisitedPerson.setText("张小红12")
            mBinding.edVisitedPersonCellphone.setText("17608433228")
        }
    }
}